import { useEffect, useState } from "react";
import {
  loadDataAPI,
  deleteByIdAPI,
  createAPI,
  updateByIdAPI,
  loadDataByIdAPI,
} from "../services/products";
import { loadDataAPI as loadCategoriesAPI } from "../services/product-categroies";
import {
  Button,
  Card,
  Space,
  Table,
  Pagination,
  Form,
  Input,
  Popconfirm,
  message,
  Modal,
  InputNumber,
  Select,
} from "antd";
import {
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import { ColumnsType } from "antd/lib/table";
import { dalImg } from "../utils/tools";
import Search from "antd/lib/input/Search";
import MyUpload from "../components/MyUpload";
import MyEditor from "../components/MyEditer";
function Products() {
  const [data, setdata] = useState();
  const [total, settotal] = useState(0); //分类总量
  const [query, setquery] = useState({ page: 1, name: "" }); //查询条件
  const [isShow, setisShow] = useState(false); //是否显示模态框
  const [imageUrl, setImageUrl] = useState<string>(""); //设置图片信息
  const [html, setHtml] = useState(""); //富文本编辑器的内容
  const [myForm] = Form.useForm();
  const [currentId, setCurrentId] = useState(-1); //当前的id，如果是修改，指定值，如果是-1表示新增
  const [categorys, setCategory] = useState([]);
  useEffect(() => {
    //初始化的时候获取商品分类数据
    loadCategoriesAPI("", 1, 1000).then((res) => {
      setCategory(res.data);
    });
  }, []);

  const columns: ColumnsType<any> = [
    {
      title: "序号",
      width: "80",
      align: "center",
      render(v, r, i) {
        return i + 1;
      },
    },
    {
      title: "名字",
      dataIndex: "name",
      width: "120px",
    },
    {
      title: "价格",
      dataIndex: "price",
      width: "120px",
    },
    {
      title: "库存",
      dataIndex: "amount",
    },
    {
      title: "分类",
      align: "center",
      width: "120px",
      render(v) {
        return v.category?.name || "暂无";
      },
    },

    {
      title: "主图",
      align: "center",
      width: "120px",
      render(v) {
        return (
          <img src={dalImg(v.coverImage)} alt={v.name} className="t-img" />
        );
      },
    },
    {
      title: "简介",
      dataIndex: "desc",
    },
    {
      title: "操作",
      align: "center",
      width: "120px",
      render(v) {
        return (
          <Space>
            <Button
              type="primary"
              icon={<EditOutlined></EditOutlined>}
              size="small"
              onClick={async () => {
                const detail = await loadDataByIdAPI(v.id);
                setisShow(true);
                setCurrentId(v.id); //设置当前ID
                myForm.setFieldsValue({
                  ...v,
                  category: v.category?.id,
                  content: detail.content,
                }); //设置表单数据
                setImageUrl(v.coverImage); //
                setHtml(detail.content); //设置富文本编辑器内容
              }}
            ></Button>
            <Popconfirm
              title="是否确认删除"
              onConfirm={async () => {
                message.success("删除成功");
                await deleteByIdAPI(v.id); //调接口删除
                //重置查询条件 ↓
                setquery({
                  name: "",
                  page: 1,
                });
              }}
            >
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined></DeleteOutlined>}
              ></Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  //根据条件变化重新获取数据
  useEffect(() => {
    loadDataAPI(query.name, query.page).then((res) => {
      setdata(res.data);
      settotal(res.total);
    });
  }, [query]);
  useEffect(() => {
    //弹出编辑窗口的时候重置数据
    if (!isShow) {
      setCurrentId(-1); //重置数据
      setImageUrl(""); //重置图片数据
      setHtml("");
    }
  }, [isShow]);
  return (
    <Card
      title="商品信息"
      extra={
        <Button
          icon={<PlusOutlined />}
          type="primary"
          onClick={() => {
            setisShow(true);
          }}
        ></Button>
      }
    >
      <Space direction="vertical" style={{ width: "100%" }}>
        <Form
          layout="inline"
          onFinish={(v) => {
            setquery({ name: v.name, page: 1 }); //重置查询条件
          }}
        >
          <Form.Item name="name">
            <Input placeholder="请输入查询关键词"></Input>
          </Form.Item>
          <Form.Item>
            <Button
              icon={<SearchOutlined />}
              type="primary"
              htmlType="submit"
            ></Button>
          </Form.Item>
        </Form>
        <Table
          columns={columns}
          dataSource={data}
          pagination={{
            total,
            showSizeChanger: false, //不显示每页数量改变功能
            onChange(page) {
              // alert(page);
              setquery({ ...query, page }); //只覆盖page属性
            },
          }}
        ></Table>
      </Space>
      <Modal
        width="80vw"
        title="编辑"
        open={isShow}
        onCancel={() => {
          return setisShow(false);
        }}
        maskClosable={false} //点击空白不消失
        destroyOnClose
        onOk={() => {
          //手动触发表单的提交事件
          myForm.submit();
        }}
      >
        <Form
          preserve={false}
          labelCol={{ span: 3 }}
          form={myForm}
          onFinish={async (v) => {
            //根据currentid判断是新增还是1修改
            if (currentId > -1) {
              await updateByIdAPI(currentId + "", {
                ...v,
                coverImage: imageUrl,
                content: html,
              });
            } else {
              //此处调接口存数据
              await createAPI({ ...v, coverImage: imageUrl, content: html });
            }
            setCurrentId(-1); //重置数据
            setisShow(false);
            message.success("保存成功");
            //重置查询条件，获取数据
            setquery({
              name: "",
              page: 1,
            });
          }}
        >
          <Form.Item
            name="name"
            label="名字"
            rules={[
              {
                required: true,
                message: "名字不能为空",
              },
            ]}
          >
            <Input placeholder="请输入内容"></Input>
          </Form.Item>
          <Form.Item label="封面">
            <MyUpload imageUrl={imageUrl} setImageUrl={setImageUrl} />
          </Form.Item>
          <Form.Item
            name="category"
            label="分类"
            rules={[
              {
                required: true,
                message: "分类不能为空",
              },
            ]}
          >
            <Select>
              {categorys.map((item: any) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="price"
            label="价格"
            rules={[
              {
                required: true,
                message: "价格不能为空",
              },
            ]}
          >
            <Input
              placeholder="请输入价格"
              prefix="￥"
              style={{ width: "50%" }}
            ></Input>
          </Form.Item>
          <Form.Item
            name="amount"
            label="库存"
            rules={[
              {
                required: true,
                message: "库存不能为空",
              },
            ]}
          >
            <InputNumber min={1} placeholder="请输入库存"></InputNumber>
          </Form.Item>
          <Form.Item name="desc" label="简介">
            <Input.TextArea placeholder="请输入简介"></Input.TextArea>
          </Form.Item>
          <Form.Item label="详情">
            <MyEditor html={html} setHtml={undefined} />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}

export default Products;
